# 导入绘图库
from PIL import Image
#导入科学计算库
import numpy as np


#封装一个图像处理工具类
class TestNumpy(object):

    def photo2paint(self,img_url):
        #读取图片，asarray()转矩阵    convert('L')转变成像素化     astype()转元素类型
        my_photo = np.asarray(Image.open(img_url).convert('L')).astype('float')
        print(my_photo)
        print(my_photo.dtype)
        print(my_photo.shape)
        print(my_photo.size)
        print('矩阵是 {} 维度'.format(my_photo.ndim))
        print('元素 {} 字节'.format(my_photo.itemsize))

        #设置灰度阈值   范围是(0-100)
        depth = 10

        #将灰度系数映射到numpy
        grad = np.gradient(my_photo)

        #获取坐标
        grad_x,grad_y = grad

        #分别处理，淡化灰度
        grad_x = grad_x * depth / 300
        grad_y = grad_y * depth / 300

        #设置阿尔法值
        #设置坐标范围
        A = np.sqrt(grad_x**2 + grad_y**2 + 1)

        #重新赋值，进行光源化处理，避免像素缺失
        uni_x = grad_x/A
        uni_y = grad_y/A
        uni_z = 1/A

        #灰度光源设置   角度/弧度
        vec_el = np.pi/2.2
        vec_az = np.pi/4

        #设置x轴和y轴
        dx = np.cos(vec_el) * np.cos(vec_az)  #余玄
        dy = np.cos(vec_el) * np.sin(vec_az)

        #设置z轴
        dz = np.sin(vec_el)

        #设置byte值
        b = 255 * (dx*uni_x+dy*uni_y+dz*uni_z)
        #光源归一化
        b = b.clip(0,255)

        #声明图像类对象
        im = Image.fromarray(b.astype('uint8'))
        #保存图像
        im.save('./test_new.jpg')


if __name__ == "__main__":
    tn = TestNumpy()
    tn.photo2paint('./news.jpg')